<template>
  <div style="width: 100%; height: calc(100% - 50px)">
    <!-- v-on="gridEvents" overflow: hidden -->
    <vxe-grid ref="tableRef" v-bind="gridOptions" v-on="gridEvents">
      <template #toolbar_buttons>
        <div style="display:flex;margin-left: 10px">
          <div>
            <span style="font-size: 15px">数据来源</span>
            <Tooltip placement="top" :overlayStyle="{ width: '200px' }">
              <template #title>
                <div>
                  <div>收款确认: 金额(人民币) = (实收金额+折扣总金额+总手续费+总金额+总佣金)*汇率</div>
                  <div>销售预收款:金额(人民币) = 预收款总金额*汇率</div>
                </div>

              </template>
              <InfoCircleOutlined style="margin-left: 5px; color: #cc8500; font-size: 19px; cursor: pointer" />
            </Tooltip>
          </div>
          <div style="display: flex;align-items: center;margin-left: 15px;">
            <span class="table-header-btn" @click="addExcludeFn">提交排除抽成</span>
            <span class="table-header-btn" @click="getExcludeFn">查看已排除数据</span>
            <span class="table-header-btn" @click="openWaitFn" v-if="waitList.length"
              style="color: orange;">查看数据处理队列</span>
          </div>
        </div>

      </template>
      <template #footer_totalAllPrice>
        <span style="color: red;">{{ totalObj.totalAllPrice }}{{ totalObj.totalAllPrice ? '元' : '' }}</span>
      </template>
      <template #footer_orderCommissionPrice>
        <span style="color: red;">{{ totalObj.orderCommissionPrice }}{{ totalObj.totalAllPrice ? '元' : '' }}</span>
      </template>
      <template #footer_receiverUserPrice>
        <span style="color: red;">{{ totalObj.receiverUserPrice }}{{ totalObj.receiverUserPrice ? '元' : '' }}</span>
      </template>
      <template #footer_merchandiserUserPrice>
        <span style="color: red;">{{ totalObj.merchandiserUserPrice }}{{ totalObj.merchandiserUserPrice ? '元' : ''
        }}</span>
      </template>
      <template #footer_manageUserPrice>
        <span style="color: red;">{{ totalObj.manageUserPrice }}{{ totalObj.manageUserPrice ? '元' : '' }}</span>
      </template>
      <template #footer_xiangMuGroupPrice>
        <span style="color: red;">{{ totalObj.xiangMuGroupPrice }}{{ totalObj.xiangMuGroupPrice ? '元' : '' }}</span>
      </template>
      <template #footer_jiJingPrice>
        <span style="color: red;">{{ totalObj.jiJingPrice }}{{ totalObj.jiJingPrice ? '元' : '' }}</span>
      </template>

    </vxe-grid>

    <div style="width: 100%;margin-top: 8px;margin-bottom: 8px;background: white;text-align: center;">
      <Button type="primary" @click="submitFn">提起审批</Button>
      <!--      <Button type="warning" @click="openWaitFn" v-if="waitList.length">还有正在等待提交处理的数据</Button>-->

    </div>

    <FormModal @register="register" @success="handleSuccess" />

    <FaPiaoItemModal @register="skrq[0]"></FaPiaoItemModal>
    <yuShouDetailModal @register="yushouModal[0]"></yuShouDetailModal>
    <ExcludeDataModal @register="excludeModal[0]" @success="handleSuccess"></ExcludeDataModal>
    <ExcludeAddModal @register="excludeAddModal[0]" @success="handleSuccess"></ExcludeAddModal>
    <Modal v-model:visible="visible" title="提示信息" @ok="handleOk">
      <p v-for="(item, index) in msgList">第{{ item.index }}行 {{ item.message }}</p>
    </Modal>

    <!-- <Modal v-model:visible="visible" title="还有正在等待提交的数据" @ok="handleOk">
      <p v-for="(item, index) in msgList">第{{ item.index }}行 {{ item.message }}</p>
    </Modal> -->
  </div>
</template>
<script lang="ts" setup>
import {
  msMoneyAffirmList, refetch, countMoneyAffirm, exportMoneyChild, addExcludeAffirmLog, trialLogList
} from '@/api/heng/ywManage';
import {
  BasicTableProps,
  VxeBasicTable,
  VxeGridInstance,
  VxeGridListeners,
  VxeTableDefines,
} from '@/components/VxeTable';
import {
  vxeTableFormSchema, exportColumns
} from './role.data';
import {
  checkboxCountFn
} from '../dknMoneyList/role.data';
//  vxeTableColumns,
import { useLocaleStore } from '@/store/modules/locale';
import { InfoCircleOutlined } from '@ant-design/icons-vue';
import { VxeFormItemProps, VxeGridPropTypes } from '@/components/VxeTable';

import { reactive, ref, unref, h, onMounted, toRaw, computed, onUnmounted } from 'vue';
import { useUserStore } from '@/store/modules/user';

import FormModal from './FormModal.vue';
import FaPiaoItemModal from './FaPiaoItemModal.vue';
import yuShouDetailModal from './yuShouDetailModal.vue';
import ExcludeDataModal from './ExcludeDataModal.vue';
import ExcludeAddModal from './ExcludeAddModal.vue';
import { useMessage } from '@/hooks/web/useMessage';
import { useModal } from '@/components/Modal';
import { Modal, Tooltip, Button } from 'ant-design-vue';

defineOptions({ name: 'MouldList' });
const { createMessage } = useMessage();
const userStore = useUserStore();

const [register, { openModal, closeModal }] = useModal();
const skrq = useModal();
const yushouModal = useModal();
const excludeModal = useModal();
const excludeAddModal = useModal();
const localeStore = useLocaleStore();

const loading = ref(false);
const visible = ref(false);
const msgList = ref([]);

const showTxtSuccess = ref(false);

const tableRef = ref<VxeGridInstance>();

const totalObj = ref({})

const waitList = ref([]);

const vxeTableColumns: VxeGridPropTypes.Columns = [

  {
    type: 'checkbox',
    title: '',
    field: 'seq',
    width: 40,
  },
  {
    title: '单据来源编号',
    field: 'orderNo',
    showOverflow: 'title',
    filters: [{ data: '' }],
    filterRender: {
      name: 'VxeInput',
    },

    slots: {
      default: ({ row }) => {
        return h('a', { onClick: () => skrqOpenFn(row) }, row.orderNo);
      },
    },
    width: 130,
  },
  {
    title: '来源类型',
    field: 'type',
    showOverflow: 'title',
    filters: [{ data: '' }],
    align: 'center',
    filterRender: {
      name: 'VxeInput',
    },
    treeNode: true,
    width: 100,
  },
  {
    title: '销售订单号',
    field: 'xiaoShouDingDanTID',
    showOverflow: 'title',
    align: 'center',
    width: 100,
    filters: [{ data: '' }],
    filterRender: {
      name: 'VxeInput',
    },
  },
  {
    title: '明细项',
    align: 'center',
    field: 'type',
    type: "expand",
    // visible: false,
    children: [
      {
        title: '发票编号',
        field: 'zhuTID',
        showOverflow: 'title',
        align: 'center',
        width: 100,
        visible: false,

      },
      {
        title: '物料编号',
        field: 'wuLiaoBianHao',
        showOverflow: 'title',
        align: 'center',
        width: 100,
        visible: false,

      },

      {
        title: '物料名称',
        field: 'wuLiaoMingCheng',
        showOverflow: 'title',
        align: 'center',
        width: 100,
        visible: false,

      },
      {
        title: '性质',
        field: 'lingYongXingZhi',
        showOverflow: 'title',
        align: 'center',
        width: 100,
        visible: false,

      },
      {
        title: '销售订单号',
        field: 'xiaoShouDingDanTID',
        showOverflow: 'title',
        align: 'center',
        width: 100,
        visible: false,
        filters: [{ data: '' }],
        filterRender: {
          name: 'VxeInput',
        },
      },

      {
        title: '确认到货金额',
        field: 'queRenDaoHuoJinE',
        showOverflow: 'title',
        align: 'center',
        width: 100,
        visible: false,

      },

      {
        title: '确认到货人民币金额',
        field: 'queRenDaoHuoRenMinBiJinE',
        showOverflow: 'title',
        align: 'center',
        width: 100,
        visible: false,

      },
    ]
  },
  {
    title: '收款日期',
    field: 'payTime',
    showOverflow: 'title',
    align: 'center',
    width: 100,
    formatter: ({ cellValue, row, column }) => {
      let val = '';
      if (!cellValue) {
        return val;
      }
      let arr = cellValue.split(" ")
      val = `${arr[0]}`;
      return val;
    },
  },
  {
    title: '客户编号',
    field: 'customerNo',
    showOverflow: 'title',
    filters: [{ data: '' }],
    align: 'center',
    filterRender: {
      name: 'VxeInput',
    },
    width: 80,
  },
  {
    title: '客户所属地区',
    field: 'diQu',
    showOverflow: 'title',
    align: 'center',
    width: 80,
  },
  {
    title: '币种',
    field: 'currencyType',
    showOverflow: 'title',
    align: 'center',
    width: 80,
  },
  {
    title: 'ms营销组',
    field: 'salesmanDeptName0',
    showOverflow: 'title',
    filters: [{ data: '' }],
    filterRender: {
      name: 'VxeInput',
    },
    width: 100,
  },
  {
    title: 'ms业务员',
    field: 'salesmanName0',
    showOverflow: 'title',
    filters: [{ data: '' }],
    filterRender: {
      name: 'VxeInput',
    },
    width: 60,
  },

  {
    title: '金额(人民币)',
    field: 'totalAllPrice',
    showOverflow: 'title',
    width: 100,
    formatter: ({ cellValue, row, column }) => {
      let val = cellValue;
      if (!cellValue) {
        return val;
      }
      if ((cellValue + "").indexOf('.') > -1) {
        val = cellValue.toFixed(2);

      }
      return val;
    },
    slots: {
      footer: "footer_totalAllPrice"
    }
  },
  {
    title: '抽成比例',
    field: 'orderCommissionRate0',
    showOverflow: 'title',
    formatter: ({ cellValue, row, column }) => {
      let val = '';
      if (!cellValue) {
        return val;
      }
      val = `${cellValue ? cellValue + '%' : cellValue + '%'}`;
      return val;
    },
    width: 100,
  },
  {
    title: '抽成金额',
    field: 'orderCommissionPrice0',
    showOverflow: 'title',
    width: 100,
    slots: {
      footer: "footer_orderCommissionPrice"
    }
  },
  {
    title: '接单人',
    field: 'receiverUserName0',
    align: 'center',
    filters: [{ data: '' }],
    filterRender: {
      name: 'VxeInput',
    },
    width: 60,
  },
  {
    title: '接单人比例',
    field: 'receiverUserRate0',
    formatter: ({ cellValue, row, column }) => {
      let val = '';
      if (!cellValue) {
        return val;
      }
      val = `${cellValue ? cellValue + '%' : cellValue + '%'}`;
      return val;
    },

    align: 'center',
    width: 60,
  },
  {
    title: '接单人抽成金额',
    field: 'receiverUserPrice0',
    align: 'center',
    width: 90,
    slots: {
      footer: "footer_receiverUserPrice"
    }
  },

  {
    title: '跟单人',
    field: 'merchandiserUserName0',
    filters: [{ data: '' }],
    filterRender: {
      name: 'VxeInput',
    },
    align: 'center',
    width: 60,
  },
  {
    title: '跟单人比例',
    field: 'merchandiserUserRate0',
    align: 'center',
    formatter: ({ cellValue, row, column }) => {
      let val = '';
      if (!cellValue) {
        return val;
      }
      val = `${cellValue ? cellValue + '%' : cellValue + '%'}`;
      return val;
    },
    width: 60,
  },
  {
    title: '跟单人抽成金额',
    field: 'merchandiserUserPrice0',
    align: 'center',
    width: 90,
    slots: {
      footer: "footer_merchandiserUserPrice"
    }
  },

  {
    title: '介绍人',
    field: 'introduceUserName',
    // filters: [{ data: '' }],
    // filterRender: {
    //   name: 'VxeInput',
    // },
    align: 'center',
    width: 60,
  },
  {
    title: '介绍人比例',
    field: 'introduceUserRate',
    align: 'center',
    formatter: ({ cellValue, row, column }) => {
      let val = '';
      if (!cellValue) {
        return val;
      }
      val = `${cellValue ? cellValue + '%' : cellValue + '%'}`;
      return val;
    },
    width: 50,
  },
  {
    title: '介绍人抽成金额',
    field: 'introduceUserPrice',
    align: 'center',
    width: 60,
    // slots: {
    //   footer: "footer_merchandiserUserPrice"
    // }
  },
  {
    title: '业务经理',
    field: 'manageUserName0',
    align: 'center',
    width: 70,
  },
  {
    title: '经理抽成',
    field: 'manageUserPrice0',
    align: 'center',
    width: 90,
    slots: {
      footer: "footer_manageUserPrice"
    }
  },
  {
    title: '项目组',
    field: 'xiangMuGroupName0',
    align: 'center',
    width: 70,
  },
  {
    title: '项目组抽成',
    field: 'xiangMuGroupPrice0',
    align: 'center',
    width: 90,
    slots: {
      footer: "footer_xiangMuGroupPrice"
    }
  },
  {
    title: '团建基金',
    field: 'jiJingName0',
    width: 100,
  },
  {
    title: '团建金额',
    field: 'jiJingPrice0',
    width: 100,
    slots: {
      footer: "footer_jiJingPrice"
    }
  },

  {
    title: 'ms审批状态',
    field: 'stateName0',
    align: 'center',
    width: 80,
  },
];


function skrqOpenFn(record) {
  if (record.type == "收款确认") {
    skrq[1].openModal(true, {
      record: toRaw(record),
    });
  } else {
    yushouModal[1].openModal(true, {
      record: toRaw(record),
    });
  }

}

const outLoadding = ref(false);

const gridOptions = reactive<BasicTableProps>({
  // keepSource: true,
  // editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
  exportConfig: {
    filename() {
      return `抽成明细导出`
    },
    isMerge: true,//合并单元格
    isAllExpand: true,//展开树
    isFooter: false,//不需要表尾
    excludeFields: ['seq', 'num'], //不需要哪些列
    // remote: true,
    // exportMethod: (params) => {
    //   // console.log("---exportMethod --", params);
    //   let dataList=params.options.data;
    //   outLoadding.value=true;
    //   return exportMoneyChild([...params.options.data]).then((res) => {
    //     outLoadding.value=false;

    //     if(res.code == 200){
    //       let data2= res.data;
    //       for(let key1 in dataList){
    //         for(let key2 in data2){
    //           if(dataList[key1].orderNo == data2[key2].skqrNo){

    //           }
    //         }
    //       }
    //     }
    //     return res;
    //   });
    // },
    // beforeExportMethod: ({ options }) => {
    //   console.log("---beforeExportMethod --");
    //   console.log(options);
    // }
  },
  expandConfig: {},
  treeConfig: {
    rowField: 'orderNo',
    childrenField: 'children',
    // expandAll: true
  },
  showFooter: true,
  footerData: [
    { seq: '合计', num: 123 }
  ],
  border: true,
  showOverflow: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: vxeTableColumns,
  filterConfig: {
    remote: true,
  },
  // checkboxConfig: {
  //   labelField: 'orderNo',
  //   highlight: true,
  //   reserve: true,
  //   // showReserveStatus: true
  // },
  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
    refresh: true,
  },
  formConfig: {
    // enabled: true,
    items: vxeTableFormSchema,
  },
  pagerConfig: {
    // pageSize: 20,
  },
  proxyConfig: {
    props: {
      result: 'data.list',
      list: 'data.list',
      total: 'data.totalResult',
      message: 'message',
    },
    filter: true,
    ajax: {
      query: ({ page, form, filters }) => {
        return findPageList(page, form, filters);
      },
      // queryAll: async ({ form }) => {
      //   return await demoListApi(form);
      // },
    },
  },
});


const gridEvents: VxeGridListeners<any> = {

  checkboxChange({ checked, row }) {

    let rows = tableRef.value?.getCheckboxRecords();
    totalObj.value = checkboxCountFn(rows);
  },
  checkboxAll({ checked, $event }) {
    let rows = tableRef.value?.getCheckboxRecords();
    totalObj.value = checkboxCountFn(rows);
  }

}

function findPageList(page, form, filterList?: VxeTableDefines.FilterCheckedParams<any>[]) {
  let json = {};
  if (filterList && filterList.length) {
    filterList.forEach((e) => {
      const value = e.datas[0];
      let field = e.field;
      json[field + 'Like'] = value;
    });
  }
  if (form.dateArr) {
    form.startTime = form.dateArr[0] + " 00:00:00";
    form.endTime = form.dateArr[1] + " 23:59:59";
  } else {
    form.startTime = "";
    form.endTime = "";
  }
  if (json.xiaoShouDingDanTIDLike) {
    tableRef.value?.setAllRowExpand(true);
  } else {
    tableRef.value?.setAllRowExpand(false);

  }
  //setAllRowExpand
  // console.log("----json:", json);
  // countMoneyAffirmFn({
  //   ...form,
  //   ...json,
  // });
  return msMoneyAffirmList({
    page: page.currentPage,
    pageSize: page.pageSize,
    ...form,
    ...json,
  });
}

const findList = (filterList?: VxeTableDefines.FilterCheckedParams<any>[]) => {
  gridOptions.loading = true;
  // 模拟接口
  let queryJson = {};
  if (filterList && filterList.length) {
    filterList.forEach((e) => {
      const value = e.datas[0];
      let field = e.field;
      queryJson[field + 'Like'] = value;
    });
  }

  return new Promise<any[]>((resolve) => {
    let pp = {
      page: { currentPage: 1, pageSize: 20 },
      form: queryJson,
    };

    gridOptions.proxyConfig.ajax.query(pp).then((res) => {
      gridOptions.loading = false;
      let resultObj = {
        result: res.data.list,
        page: {
          total: res.data.totalResult,
        },
      };

      resolve(res);
    });
  });
};
var interval = 0;
onMounted(() => {
  // findList();
  refetch();
//  startInterval();
});

onUnmounted(() => {
  closeInterval();
})

function startInterval() {
  interval = setInterval(() => {
    if (openNum == 0) {
    }
    trialLogListFn();

  }, 3000);
}

function closeInterval() {
  clearInterval(interval);
}


function handleClose(record: Recordable) {
  //console.log(record);


}

function handleSuccess() {
  tableRef.value.commitProxy('reload');
}
var openNum = 0;

function handleOk() {
  visible.value = false;
}

function handleSuccessOk() {
  showTxtSuccess.value = false;
}

function countMoneyAffirmFn(json) {
  countMoneyAffirm(json)
    .then((res) => {
      if (res.code == 200) {
        // console.log("---countMoneyAffirm");
        // console.log(res.data);
        res.data.totalAllPrice = res.data.totalAllPrice.toFixed(2);
        totalObj.value = res.data;
      } else {
        createMessage.error(res.message);
      }
    })
    .catch((res) => {
      createMessage.error(res.message);
    })
    .finally(() => {
    });
}


function trialLogListFn() {
  trialLogList({ type: 1 })
    .then((res) => {
      if (res.code == 200) {
        waitList.value = res.data;
        // console.log("--res.data:", res.data);

        localeStore.setWaitList(res.data)
      }
    });

}


function submitFn() {

  const selectRecords = tableRef.value.getCheckboxRecords();
  const selectReserveRecords = tableRef.value.getCheckboxReserveRecords();

  let selectList = [...selectRecords, ...selectReserveRecords];

  openNum = 1;
  openModal(true, {
    selectList: unref(selectList),
    type: 1
  });

  if(!interval){
    startInterval();
  }

}

function addExcludeFn() {
  const selectRecords = tableRef.value.getCheckboxRecords();
  const selectReserveRecords = tableRef.value.getCheckboxReserveRecords();

  let selectList = [...selectRecords, ...selectReserveRecords];

  if (selectList.length == 0) {
    createMessage.error('请选择要排除的数据!');
    return;
  }
  excludeAddModal[1].openModal(true, {
    selectList: unref(selectList)
  });
  // addExcludeAffirmLog({ list: selectList }).then(res => {
  //   if (res.code == 200) {
  //     createMessage.success(res.message);
  //     tableRef.value.commitProxy('reload');
  //   } else {
  //     createMessage.error(res.message);
  //   }
  // })
}

function getExcludeFn() {
  excludeModal[1].openModal(true, { types: "收款确认,预收款" })
}
function openWaitFn() {
  let parameter = waitList.value[0].list;
  let selectList = JSON.parse(parameter);
  openNum = 1;
  openModal(true, {
    selectList,
    type: 1,
    wait: true
  });
}


</script>
<style lang="less">
.isReturn_clazz {
  text-align: center;
  cursor: pointer;
}

.table-header-btn {
  padding-left: 10px;
  color: gray;
  font-size: 12px;
  cursor: pointer;
}
</style>
